package org.springframework.samples.petclinic.hibernate

import java.util.Collection

import org.hibernate.SessionFactory 

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional

import org.springframework.samples.petclinic.Clinic
import org.springframework.samples.petclinic.Owner
import scala.reflect.BeanProperty

@Repository
@Transactional
class HibernateClinic extends Clinic {

  var sessionFactory:SessionFactory = null
  
  @Autowired 
  def setSessionFactory(sessionFactory:SessionFactory) = {
    this.sessionFactory = sessionFactory
  }
  
  @Transactional{val readOnly = true}
  def getVets(): Collection[Vet] = {
    sessionFactory.getCurrentSession().createQuery("from Vet vet order by vet.lastName, vet.firstName").list().asInstanceOf[Collection[Vet]]
  }
  
  @Transactional{val readOnly = true}
  def getPetTypes(): Collection[PetType] = {
    sessionFactory.getCurrentSession().createQuery("from PetType type order by type.name").list().asInstanceOf[Collection[PetType]]
  }

  @Transactional{val readOnly = true}
  def findOwners(lastName:String): Collection[Owner] = {
    sessionFactory.getCurrentSession().createQuery("from Owner owner where owner.lastName like :lastName")
        .setString("lastName", lastName + "%").list().asInstanceOf[Collection[Owner]]
  }
  
  @Transactional{val readOnly = true}
  def loadOwner(id:Int): Owner = {
    sessionFactory.getCurrentSession().load(classOf[Owner], id).asInstanceOf[Owner]
  }
  
  @Transactional{val readOnly = true}
  def loadPet(id:Int): Pet = {
    sessionFactory.getCurrentSession().load(classOf[Pet], id).asInstanceOf[Pet]
  }
  
  def storeOwner(owner:Owner) {
    sessionFactory.getCurrentSession().merge(owner)
  }

  def storePet(pet:Pet) {
    sessionFactory.getCurrentSession().merge(pet)
  }
  
  def storeVisit(visit:Visit) {
    sessionFactory.getCurrentSession().merge(visit)
  }

}
